from flask import Blueprint,request,jsonify
from utils.db import db
from utils.comm import get_data,xtree
from utils.comm import access_key,secret_key
#七牛云
from qiniu import Auth

import json
import os
bp_course = Blueprint('course',__name__)


#无限级分类
@bp_course.route('/cates/',methods=["POST","GET","DELETE"])
def cates():
    if request.method =="POST":
        data = get_data()
        sql = "insert into cates values(0,'%s',%d,%s) "%(data['name'],int(data['pid']),data['params'])
        
        db.insert(sql)
        return jsonify({"code":200})

    elif request.method =="GET":
        #获取全部数据
        sql = "select * from cates"
        res = db.find_all(sql)
        print(res)
        
        list = xtree(res)
        return jsonify({'code':200,'list':list})
    else:
        pass

#分页
@bp_course.route('/pageshow/',methods=["POST","GET","DELETE"])
def pageshow():
    if request.method =="POST":
        pass
    elif request.method =="GET":
        pagesize = int(request.args.get('page_size'))
        page = request.args.get('page')
        start = (int(page)-1)*pagesize

        sql = "select * from cates  order by id asc limit %d,%d"%(start,pagesize)
        res = db.find_all(sql)
        sql1 = "select count(id) as total from cates"
        res1 = db.find_one(sql1)
        print(res)
        return jsonify({"code":200,'list':res,'total':res1['total']})
    else:
        pass


#讲师展示添加
@bp_course.route('/teaadd/',methods=["POST","GET","DELETE"])
def teaadd():
    if request.method =="POST":
        data = get_data()
        if data['params']:
            sql = "insert into courses values(%d,'%s',%d,'%s','%s','%s',%d,%d)"%(0,data['title'],int(data['pid']),data['params'],data['pic'],data['descip'],int(data['teacher_id']),int(data['status']))
        else:
            sql = "insert into courses(`title`,`pid`,`pic`,`descip`,`teacher_id`,`status`) values('%s',%d,'%s','%s',%d,%d)"%(data['title'],int(data['pid']),data['pic'],data['descip'],int(data['teacher_id']),int(data['status']))
        db.insert(sql)
        return jsonify({"code":200})
    elif request.method =="GET":
        id =request.args.get('id')
        sql = "select * from cates where id=%d"%(int(id))
        res= db.find_one(sql)
        return jsonify({'code':200,'params':res['params']})
    else:
        pass

#coures 数据库的分页展示    章节添加
@bp_course.route('/courserpage/',methods=["POST","GET"])
def courserpage():
    if request.method =="POST":
        data = get_data()
        sql = "insert into jie values(0,'%s',%d,'%s',%d)"%(data['name'],int(data['course_id']),data['video_url'],int(data['sort']))
        print(sql)
        db.insert(sql)
        return jsonify({"code":200})
    elif request.method =="GET":
        #获取每页数据条数
        pagesize = int(request.args.get('page_size'))
        #获取数据当前页数
        page = request.args.get('page')
        #每页数据第一个数据下表
        start = (int(page)-1)*pagesize
        #构建sql查询
        sql  = "select l.title,l.pic,c.name from courses as l left join cates as c on l.pid=c.id limit %d,%d"%(start,pagesize)     
        res = db.find_all(sql)
        #查询数据总条数 用于前台显示
        sql1 = "select count(id) as total from courses"
        res1 = db.find_one(sql1)

        return jsonify({"code":200,'list':res,'total':res1['total']})

#获取七牛云的token
@bp_course.route('/qntoken/')
def qntoken():
    q = Auth(access_key,secret_key)
    #要上传的空间
    bucket_name = 'yangceshi'
    #生成上传token
    token = q.upload_token(bucket_name)
    return jsonify({"code":200,'token':token})

#章节表添加数据 展示
@bp_course.route('/jieadd/',methods=['POST','GET'])
def jieadd():
    if request.method =="POST":
        #接收视频流
        file = request.files['file']
        #接收课程id
        course_id = request.form['course_id']
        #写文件吧视频放在本地
        path = "./static/upload/"+str(course_id)
        #判断有没有地址 没有创建地址 有进行添加数据
        if not os.path.exists(path):
            os.mkdir(path)
        #保存视频
        file.save(os.path.join(path,file.filename))
        return jsonify({"code":200,'url':"/static/upload/"+str(course_id)+'/'+file.filename})


    elif request.method =="GET":
        #获取课程
        sql = "select * from courses "
        res = db.find_all(sql)
        return jsonify({"code":200,'list':res})
